package com.geez.bbl.pdf;
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

import com.geez.bbl.db.type.BblBook;
import com.geez.bbl.db.type.BblChapter;
import com.geez.bbl.db.type.Builder;
import com.geez.bbl.db.type.Verse;
import com.geez.bbl.util.ProjectResources;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Bbl2Pdf {

    public static String monouniFile = ProjectResources.getResourceFile("itext", "fonts", "CODE2000.ttf").getAbsolutePath();
    public static String mahtemaFile = ProjectResources.getResourceFile("itext", "fonts", "GeezMahtemUnicode.ttf").getAbsolutePath();
    public static String nyalaFile = ProjectResources.getResourceFile("itext", "fonts", "nyala.ttf").getAbsolutePath();
    public static Font monouni = FontFactory.getFont(monouniFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 11);
    public static Font nyala = FontFactory.getFont(nyalaFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 11);
    public static Font nyalaBook = FontFactory.getFont(mahtemaFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 20, Font.BOLDITALIC);
    public static Font nyalaChap = FontFactory.getFont(nyalaFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 14);

    public static final String HEAD = ProjectResources.getResourceFile("itext", "heading.pdf").getAbsolutePath();
    public static final File BODY = ProjectResources.getResourceFile("itext", "ipadTigrignaBible.pdf");

    Document document;
    PdfWriter writer;
    TableOfContent event = new TableOfContent();


    public Bbl2Pdf() throws DocumentException, IOException {
        document = new Document(PageSize.B5);
        writer = PdfWriter.getInstance(document, new FileOutputStream(BODY));
        writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
        Rectangle rectangle = new Rectangle(48, 48, 420, 658);
        writer.setBoxSize("art", rectangle);
         writer.setLinearPageMode();
        writer.setPageEvent(new HeaderFooter());
        document.open();
        addMetaData(document);
        document.setMargins(70, 70, 60, 30);
        document.setMarginMirroring(true);
        writer.setPageEmpty(false);

        PdfImportedPage page = writer.getImportedPage(new PdfReader(HEAD), 1);
        writer.getDirectContent().addTemplate(page, 0, 0);
        document.newPage();
        PdfImportedPage page2 = writer.getImportedPage(new PdfReader(HEAD), 2);
        writer.getDirectContent().addTemplate(page2, 0, 0);
    }

    public static void main(String[] args) throws Exception {
        List<BblBook> books = new Builder("ti").build();
        new Bbl2Pdf().createPdf(books);
    }


    public void createPdf(List<BblBook> bblBooks) throws DocumentException, IOException {

        initKidan(bblBooks.subList(0, 38), document, makeKidanTitle("ብሉይ ኪዳን", "Old Testament"));
        initKidan(bblBooks.subList(38, bblBooks.size()), document, makeKidanTitle("ሓድሽ ኪዳን", "New Testament"));

      //  applyTOC();

        document.close();
    }

    private void applyTOC() throws DocumentException {
        document.newPage();
        int toc = writer.getPageNumber();
        for (Phrase p : event.titles) {
            document.add(p);
        }
        // always go to a new page before reordering pages.
        document.newPage();
        // get the total number of pages that needs to be reordered
        int total = writer.reorderPages(null);
        // change the order
        int[] order = new int[total];
        for (int i = 0; i < total; i++) {
            order[i] = i + toc;
            if (order[i] > total)
                order[i] -= total;
        }
        // apply the new order
        writer.reorderPages(order);
    }


    private static void addMetaData(Document document) {
        document.addTitle("Tigrigna Bible");
        document.addSubject("Using iText");
        document.addKeywords("Tigrigna, Tigrinya, Bible, Geez");
        document.addAuthor("Biniam Gebremichael <biniamg@gmail.com>");
    }

    private void initKidan(List<BblBook> bblBooks, Document document, Chapter k) throws DocumentException {
        for (int i = 0; i < bblBooks.size(); i++) {
            if (i > 0) {
                k.newPage();
            }
            getBookPdf(k, bblBooks.get(i));
        }
        document.add(k);
    }

    private Section getBookPdf(Chapter k, BblBook bblBook) throws DocumentException {
        Paragraph bookTitle = makeBookTitle(bblBook);
        Section book = k.addSection(bookTitle, 0);
        //  book.setTitle(new Paragraph(bookTitle));
        book.setBookmarkTitle(bblBook.getEnglishName());
        book.setBookmarkOpen(false);
        book.setNumberDepth(0);

        for (BblChapter bblChapter : bblBook.getChapters().values()) {
            Paragraph chapterTitle = makeChapterTitle(bblChapter.getId());
            Section chapter = book.addSection(chapterTitle);
            chapter.setBookmarkTitle("Chapter " + bblChapter.getId());
            //    chapter.setTitle(chapterTitle);
            chapter.setNumberDepth(0);
            chapter.addAll(getChapterPdf(bblChapter));
        }
        return book;
    }

    private List<Paragraph> getChapterPdf(BblChapter bblChapter) {
        List<Paragraph> vers = new ArrayList<Paragraph>();
        vers.add(new MyParagraph());
        for (Verse verse : bblChapter.getVerses()) {
            if (verse.isParagraph()) {
                vers.add(new MyParagraph());
            }
            String num = verse.getStartId() == verse.getEndId() ? String.valueOf(verse.getStartId()) : verse.getStartId() + "-" + verse.getEndId();
            vers.get(vers.size() - 1).add(makeVerse(num, verse.getValue()));
        }
        return vers;
    }

    private Paragraph makeBookTitle(BblBook bblBook) {
        Paragraph title = new Paragraph(bblBook.getLong_name(), nyalaBook);
        title.setSpacingAfter(10);
        title.setAlignment(Element.ALIGN_CENTER);
        return title;
    }

    private Paragraph makeChapterTitle(int number) {
        Paragraph cabecalho = new Paragraph();
        cabecalho.add(new Chunk("ምዕራፍ", nyalaChap));
        cabecalho.add(new Chunk(" " + number + " ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 13)));
        cabecalho.setSpacingBefore(20);
        cabecalho.setSpacingAfter(2);
        cabecalho.setAlignment(Element.ALIGN_CENTER);
        return cabecalho;
    }

    private Chapter makeKidanTitle(String title, String enTitle) {
        // Paragraph cabecalho = new Paragraph(title,nyala);
        Chapter kidan = new Chapter(title, 1);
        kidan.setNumberDepth(0);
        kidan.setBookmarkOpen(false);
        kidan.setBookmarkTitle(enTitle);

        return kidan;
    }


    private Phrase makeVerse(String number, String value) {
        Phrase cabecalho = new Phrase();
        Chunk fqdi = new Chunk(" " + number + " ", FontFactory.getFont(FontFactory.HELVETICA, 6, Font.ITALIC));
        fqdi.setTextRise(5f);
        cabecalho.add(fqdi);
        cabecalho.add(new Phrase(value, nyala));
        return cabecalho;
    }

    class MyParagraph extends Paragraph {
        MyParagraph() {
            setSpacingBefore(8);
            setAlignment(Element.ALIGN_JUSTIFIED);
        }
    }
}